<template>
  <div class="yxp">
    <top-back :title="'Unit' + (square_type - 1)" type="2"></top-back>
    <word-list :dataList="dataList" v-if="dataList.length > 0" :isFinished="isFinished" @handleMoreClick="handleMoreClick"></word-list>
    <Empty v-if="isNone" />
      <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>
import TopBack from '@/components/TopBack.vue'
import WordList from '@/components/WordList.vue'
import Empty from '@/components/Empty.vue'
import { squareWord } from '@/services/word.js'
import Timetips from "@/components/Timetips";
export default {
  name: 'wordIndex',
  components: {
    TopBack,
    WordList,
    Empty,
    Timetips
  },
  data () {
    return {
      title: '',
      package_id: 0,
      square_type: 0,
      dataList: [],
      isNone: false,
      pageIndex: 1,
      isFinished: false
    }
  },
  created () {
    if (this.$route.query) {
      let query = this.$route.query
      this.package_id = query.package_id
      this.square_type = query.square_type
    }
    this.getWordList()
  },
  mounted () {
    // window.addEventListener('scroll', this.handleScroll,true)
  },
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
  methods: {
    async getWordList () {
      this.$loading.show()
      let params = {
        package_id: this.package_id,
        square_type: this.square_type,
        page: this.pageIndex
      }
      let data = await squareWord(params)
      if (data.code === 1) {
        this.$loading.hide()
        if (data.data.length === 0) {
          if (this.pageIndex === 1) {
            this.isNone = true
          } else {
            this.isFinished = true
            // window.removeEventListener('scroll', this.handleScroll)
          }
          return
        }
        this.dataList = [...this.dataList,...data.data]
        this.$nextTick(() => {
          if (this.dataList.length < 7) {
              this.isFinished = true
            } else {
              this.isFinished = false
            }
        })
      } else if (data.code === '10001' || data.code === 10001) {
        this.$loading.hide()
        this.$toast('token过期，请重新登录')
      } else {
        this.$loading.hide()
        this.$toast(data.info)
      }
    },
    handleScroll() {
      let scrollDom = document.getElementById('wordBox')
      if (scrollDom.scrollTop > 0) {
        if (scrollDom.clientHeight + parseInt(scrollDom.scrollTop) >  scrollDom.scrollHeight - 10) {
          if (!this.isFinished) {
            this.pageIndex++
            this.isFinished = true
            this.getWordList()
          }
        }
      }
    },
    handleMoreClick() {
        if (!this.isFinished) {
          this.pageIndex++
          this.isFinished = true
          this.getWordList()
        }
    }
  }
}
</script>
